import { Table, TableProps } from "antd";
import React, {
  ReactNode,
  useState,
  forwardRef,
  useImperativeHandle,
  useMemo,
} from "react";

interface IPageParams {
  pageIndex: number;
  pageSize: number;
}

export interface IRefTableProps {
  resetTablePageSize(): void;
}

export interface ITableConfig<T = any> {
  rowKey: string;
  tableLayout?: "auto" | "fixed";
  columns: TableProps<T>["columns"];
}

interface IBmTableProps {
  tableConfig: ITableConfig;
  data: any[];
  total: number;
  loading: boolean;
  onChange?: (params: IPageParams) => void;
  ref?: any;
  customBodyComponents?: (props: any) => ReactNode;
  showPagination?: boolean;
  [prop: string]: any;
}

const BmTable: React.FC<IBmTableProps> = forwardRef(
  (
    {
      tableConfig,
      data,
      total,
      loading,
      onChange,
      customBodyComponents,
      showPagination = true,
      ...restProps
    },
    ref
  ) => {
    const [pageParams, setPageParams] = useState<IPageParams>({
      pageIndex: 1,
      pageSize: 10,
    });

    // 自定义插槽
    tableConfig.columns = useMemo(() => {
      return tableConfig.columns.map((col: any) => {
        if (col.dataIndex.includes("custom")) {
          Reflect.ownKeys(restProps).forEach((key) => {
            if (col.dataIndex === key) {
              col.render = restProps[key as string];
            }
          });
        }
        return col;
      });
    }, [tableConfig.columns])

    // 暴露组件自身方法供父组件调用
    useImperativeHandle(
      ref,
      () => ({
        resetTablePageSize() {
          setPageParams({
            pageIndex: 1,
            pageSize: 10,
          });
        },
      }),
      []
    );

    return (
      <div className="bm-table-wrapper">
        <Table
          columns={tableConfig.columns}
          dataSource={data}
          bordered
          sticky
          loading={loading}
          rowKey={tableConfig.rowKey}
          tableLayout={tableConfig.tableLayout || "fixed"}
          scroll={{ scrollToFirstRowOnChange: true, y: "calc(100% - 55px)" }}
          pagination={showPagination && {
            current: pageParams.pageIndex,
            showSizeChanger: true,
            pageSize: pageParams.pageSize,
            showQuickJumper: true,
            total,
            pageSizeOptions: ["10", "30", "50", "80", "100"],
            showTotal: (total) => `共 ${total} 项数据`,
            onChange(page, size) {
              setPageParams({
                pageIndex: page,
                pageSize: size,
              });
              if (onChange) {
                onChange({
                  pageIndex: page,
                  pageSize: size,
                });
              }
            },
          }}
          components={
            customBodyComponents
              ? {
                body: {
                  row: customBodyComponents,
                },
              }
              : undefined
          }
        />
      </div>
    );
  }
);

BmTable.displayName = "BmTable";

export default BmTable;
